//
//  EncyMyCommentViewController.m
//  安好
//
//  Created by lianchuang on 14-12-12.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "EncyMyCommentViewController.h"
#import "HospitalCommentViewCell.h"
#import "EncyCommentFirstCell.h"
#import "EncyCommentModal.h"
#import "EncyWriteCommentViewController.h"
#import "EncyWriteComment6PlusViewController.h"

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

@interface EncyMyCommentViewController ()<UITableViewDataSource,UITableViewDelegate,EncyWriteCommentViewControllerDelegate,EncyWriteComment6PlusViewControllerDelegate>

@property(nonatomic,strong)UITableView * tableView;

@property(nonatomic,assign)NSInteger loadPage;

@property(nonatomic,strong)NSMutableArray * dataArray;

@property(nonatomic,strong)UIButton * myCommentButton;

@property(nonatomic,strong)NSDictionary * AllCommentDic;

@end

@implementation EncyMyCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hiddenLabel];
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
}

#pragma mark - 导航条设置
-(void)makeNavBar
{
    self.navigationItem.title = @"我要点评";
    //左按钮--返回
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backClicked)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}
/**
 * 返回
 */
-(void)backClicked
{
    [self.delegate loadRequestForUploadCommentCount];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)loadData
{
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    self.loadPage = 1;
    [self AFNetRequestorCommentWothHosDocDes];
    
}
-(void)AFNetRequestorCommentWothHosDocDes
{
    NSString *postURL = [NSString stringWithFormat:@"%@wiki/hospitalComment/",kBaseURL];
    NSMutableDictionary * parameters = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [parameters setValue:self.commentId forKey:self.commentKey];
    [parameters setValue:self.type forKey:@"type"];
    [parameters setValue:kPlatform forKey:@"platform"];
    [parameters setValue:kVersion forKey:@"version"];
    [parameters setValue:[NSString stringWithFormat:@"%d",self.loadPage] forKey:@"page"];
    [self showActionView];
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        MyNSLog("成功");
        [self hiddenActionView];
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            MyNSLog("%@", responseObject[@"msg"]);
            if (self.loadPage == 1 && self.dataArray.count == 0) {
                [self shouLabel:@"暂无评论"];
            }
            [self.tableView footerEndRefreshing];
        }else
        {
            [self hiddenLabel];
            self.AllCommentDic = responseObject[@"data"];
            NSArray * hospitalArray = self.AllCommentDic[@"commentdata"];
            if (hospitalArray != nil )
            {
                self.loadPage ++;
                for (NSDictionary * dic in hospitalArray) {
                    EncyCommentModal * modal = [[EncyCommentModal alloc] initWithDic:dic];
                    [self.dataArray addObject:modal];
                }
                [self.tableView reloadData];
            }
            else if([hospitalArray count]< 20)
            {
                
                [self.tableView footerEndRefreshing];
            }
            else
            {
                if (self.loadPage > 1) {
                    MyNSLog("下拉无数据");
                }
            }
            [self.tableView footerEndRefreshing];
            
        }
        
  
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
        [self.tableView footerEndRefreshing];
    }];


}


#pragma mark - 创建tableView 设置代理添加头视图
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin)style:UITableViewStyleGrouped];
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorColor:[UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0]];
    [self.tableView addFooterWithTarget:self action:@selector(AFNetRequestorCommentWothHosDocDes)];
    
    //我要评论按钮
    self.myCommentButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.myCommentButton.frame = CGRectMake(15, kScreenHeight-iOS7TopMargin-54, kScreenWidth-30, 44);
    self.myCommentButton.titleLabel.font =[UIFont systemFontOfSize:15] ;
    if (IPhone6Plus) {
        self.myCommentButton.frame =CGRectMake(20, kScreenHeight-iOS7TopMargin - 70, kScreenWidth-40, 53);
        self.myCommentButton.titleLabel.font =[UIFont systemFontOfSize:17] ;
    }
    [self.view addSubview:self.myCommentButton];
    self.myCommentButton.backgroundColor = [UIColor colorWithRed:61/255.0 green:179/255.0 blue:230/255.0 alpha:1];
    [self.myCommentButton setTitle:@"我要点评" forState:UIControlStateNormal];
    [self.myCommentButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.myCommentButton addTarget:self action:@selector(myCommentButtonClicked) forControlEvents:UIControlEventTouchUpInside];
}
//“我要点评”按钮触发
-(void)myCommentButtonClicked{
    /**
     *  判断是否登录
     */
    [self isLogin];
}
/**
 *  登录之后才可以点评
 */
- (void)Login{
    
    if (IPhone6Plus) {
        EncyWriteComment6PlusViewController * goCom6 = [[EncyWriteComment6PlusViewController alloc] init];
        goCom6.delegate = self;
        goCom6.commentKey = self.commentKey;
        goCom6.commentId = self.commentId;
        goCom6.type = self.type;
        [self.navigationController pushViewController:goCom6 animated:YES];
        
    }else{
    
        EncyWriteCommentViewController * goCom = [[EncyWriteCommentViewController alloc] init];
        goCom.delegate = self;
        goCom.commentKey = self.commentKey;
        goCom.commentId = self.commentId;
        goCom.type = self.type;
        [self.navigationController pushViewController:goCom animated:YES];
    }

}

//各段有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else
    {
        return self.dataArray.count;
    }
}
//有多少段
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
//段头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (IPhone6Plus) {
        return 12;
    }else{
        return 10;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        if (IPhone6Plus) {
            return 85;
        }else{
            return 70;
        }
    }else
    {
         return 0.01;
    }
    
}
//
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (IPhone6Plus) {
            return 115;
        }else{
            return 95;
        }
        
    }else
    {
        HospitalCommentViewCell * cell = (HospitalCommentViewCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        CGFloat height = cell.userComment.bottom+15;
        return height;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        EncyCommentFirstCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"EncyCommentFirstCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"EncyCommentFirstCell" owner:self options:nil] firstObject];
            }
        }
    
        [self createStarOnSuperView:cell.ComStarFirstView andScore:self.AllCommentDic[@"environment_score"]];
        [self createStarOnSuperView:cell.ComStarSecView andScore:self.AllCommentDic[@"effect_score"]];
        [self createStarOnSuperView:cell.ComStarThirView andScore:self.AllCommentDic[@"sercice_score"]];
        NSString * score = [NSString stringWithFormat:@"%.1f",[self.AllCommentDic[@"score"] doubleValue]];
        
        cell.CommentScoreLable.text = score;
        
        return cell;
    }else
    {
        static NSString *indentifier=@"cellw";
        HospitalCommentViewCell *encycommentCell=[tableView  dequeueReusableCellWithIdentifier:indentifier];
        if (encycommentCell==nil) {
            if (IPhone6Plus) {
                encycommentCell=[[[NSBundle mainBundle] loadNibNamed:@"HospitalCommentViewCell" owner:self options:nil]lastObject];
            }else{
                encycommentCell=[[[NSBundle mainBundle] loadNibNamed:@"HospitalCommentViewCell" owner:self options:nil]firstObject];
            }
        }
        EncyCommentModal * modal = self.dataArray[indexPath.row];
        [encycommentCell.userImageview setImageWithURL:[NSURL URLWithString:modal.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
        encycommentCell.userImageview.layer.cornerRadius=3;
        encycommentCell.userImageview.layer.masksToBounds=YES;
        
        encycommentCell.userName.text = modal.username;
        encycommentCell.userComment.text =[modal.comment stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        encycommentCell.dateLine.text = modal.dateline;
        encycommentCell.dateLine.right = kScreenWidth - 15;
        encycommentCell.userName.left = encycommentCell.userImageview.right+15;
        encycommentCell.userComment.left =encycommentCell.userName.left;
        encycommentCell.userComment.width = kScreenWidth - 15-encycommentCell.userComment.left;
        if (IPhone6Plus) {
            encycommentCell.userImageview.left = 20;
            encycommentCell.userComment.width =kScreenWidth - 20-encycommentCell.userComment.left;
            encycommentCell.dateLine.right = kScreenWidth - 20;
        }
        [self autosizeFontAndSize:encycommentCell.userComment withText:modal.comment];
        
        return encycommentCell;
    
    }
    
}

-(void)createStarOnSuperView:(UIView*)view andScore:(NSString *)score
{
    CGFloat starW = 12;
    CGFloat inter = 5;
    if (IPhone6Plus) {
        starW = 15;
        inter = 10;
    }
    for (NSInteger i = 1; i <= 5; i++) {
        UIImageView * imgview = [[UIImageView alloc] initWithFrame:CGRectMake((starW+inter)*i, 0, starW, starW)];
        if (i >[score intValue] ) {
            [imgview setImage:[UIImage imageNamed:@"公用_灰星星.png"]];
        }else
        {
            [imgview setImage:[UIImage imageNamed:@"公用_黄星星.png"]];
        }
        imgview.left = imgview.left - starW-inter;
        [view addSubview:imgview];
        
    }


}

-(void)reloadCommentListView
{
    self.loadPage = 1;
    [self.dataArray removeAllObjects];
    [self AFNetRequestorCommentWothHosDocDes];
}
-(void)plusReloadCommentListView
{
    self.loadPage = 1;
    [self.dataArray removeAllObjects];
    [self AFNetRequestorCommentWothHosDocDes];
}
#pragma mark Lable自适应高度
- (void)autosizeFontAndSize:(UILabel *)label withText:(NSString *)text
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    label.attributedText = attributedString;
    [label sizeToFit];
}

@end
